package com.seek.inter;

import static com.seek.service.imp.CarrierAuthCheckImpl.getMD5Sign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seek.authcheck.constants.AuthProductEnum;
import com.seek.authcheck.constants.NoticeConstant;
import com.seek.authcheck.constants.NoticeErrorCode;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.entity.TBizFlow;
import com.seek.service.BaseAuthCheckService;
import com.seek.service.BizFlowService;
import com.seek.util.MD5Util;
import com.sinovatech.common.config.GlobalConfig;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 接收第三方回调通知
 * Created by weh on 2017/7/4.
 */

@Controller
@RequestMapping("/notice")
public class NoticeController {

  @Resource
  private BizFlowService bizFlowService;


  private static Logger logger = LoggerFactory.getLogger(NoticeController.class);


  /**
   * 接收身份认证通知
   **/
  @RequestMapping(value = "/getnotice", method = RequestMethod.POST)
  public void getAuthNotice(HttpServletRequest request, HttpServletResponse response) {
    try {
      String bodyText = getRequestStr(request);
      JSONObject reqObject = (JSONObject) JSONObject.parse(bodyText);
//      logger.info("body:{}", reqObject);
      JSONObject respJson = new JSONObject();
      //验签
      String sign = reqObject.getString(NoticeConstant.SIGN);
      String sign_time = reqObject.getString(NoticeConstant.SIGN_TIME);
      String bizNo = reqObject.getString(NoticeConstant.PARTNER_ORDER_ID);
      String signMD5 = getMD5Sign(
          GlobalConfig.getProperty(NoticeConstant.PROP_NAME, NoticeConstant.PUB_KEY), bizNo,
          sign_time,
          GlobalConfig.getProperty(NoticeConstant.PROP_NAME, NoticeConstant.SECURITY_KEY));
      if (!sign.equals(signMD5)) {
        logger.error("异步通知签名错误,对方签名:{},我方验签签名:{}", sign, signMD5);
        respJson.put(NoticeConstant.ACK_CODE, NoticeErrorCode.SIGN_ERROR.getCode());
        respJson.put(NoticeConstant.ACK_MSG, NoticeErrorCode.SIGN_ERROR.getMessage());
      } else {
        logger.info("收到商户异步通知");
        respJson.put(NoticeConstant.ACK_CODE, NoticeErrorCode.SUCCESS.getCode());
        respJson.put(NoticeConstant.ACK_MSG, NoticeErrorCode.SUCCESS.getMessage());

        BaseAuthCheckService authCheckService = SpringContextHolder
            .getBean(AuthProductEnum.CERTCARD.getCheckBeanName());
        authCheckService.autoCheck(reqObject);
      }
      logger.info("返回结果：" + respJson.toJSONString());
      response.setCharacterEncoding(NoticeConstant.CHARSET_UTF8);
      response.setContentType(NoticeConstant.CONTENT_TYPE);
      response.getOutputStream()
          .write(respJson.toJSONString().getBytes(NoticeConstant.CHARSET_UTF8));
    } catch (Exception e) {
      logger.error("出错了", e);
    }


  }

  @RequestMapping(value = "/collect/getnotice", method = RequestMethod.POST)
  public void getCollectNotice(HttpServletRequest request, HttpServletResponse response) {
    try {
      String bodyText = getRequestStr(request);
      JSONObject reqObject = (JSONObject) JSONObject.parse(bodyText);
//      logger.info("body:{}", reqObject);
      JSONObject respJson = new JSONObject();
      //验签
      String sign = reqObject.getString(NoticeConstant.SIGN);
      String productCode = reqObject.getString(NoticeConstant.TYPE);
      AuthProductEnum authProductEnum = AuthProductEnum
          .getAuthProductByProcuctCode(productCode);
      if (null == authProductEnum) {
        logger.error("没有找到{}对应的认证产品", productCode);
        return;
      }
      //收到数据采集通知不需要验签(ps：因为需要我方发送签名请求到对方获取采集数据)
//      String signText = bodyText + "|" + GlobalConfig
//          .getProperty(NoticeConstant.PROP_NAME, NoticeConstant.SECURITY_KEY);
//      logger.info(signText);
//      String signMD5 = MD5Util.MD5(signText);
//
//      if (!sign.equals(signMD5)) {
//        logger.error("异步通知签名错误,对方签名:{},我方验签签名:{}", sign, signMD5);
//        respJson.put(NoticeConstant.ACK_CODE, NoticeErrorCode.SIGN_ERROR.getCode());
//        respJson.put(NoticeConstant.ACK_MSG, NoticeErrorCode.SIGN_ERROR.getMessage());
//      } else {
        logger.info("收到商户异步通知");
        respJson.put(NoticeConstant.ACK_CODE, NoticeErrorCode.SUCCESS.getCode());
        respJson.put(NoticeConstant.ACK_MSG, NoticeErrorCode.SUCCESS.getMessage());

        BaseAuthCheckService authCheckService = SpringContextHolder
            .getBean(AuthProductEnum.getAuthProductByProcuctCode(productCode).getCheckBeanName());
        authCheckService.autoCheck(reqObject);
//      }

      logger.info("返回结果：" + respJson.toJSONString());
      response.setCharacterEncoding(NoticeConstant.CHARSET_UTF8);
      response.setContentType(NoticeConstant.CONTENT_TYPE);
      response.getOutputStream()
          .write(respJson.toJSONString().getBytes(NoticeConstant.CHARSET_UTF8));
    } catch (Exception e) {
      logger.error("出错了", e);
    }
  }


  public static String getRequestStr(HttpServletRequest request) throws IOException {
    InputStream in = request.getInputStream();
    byte[] b = new byte[10240];
    int len;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((len = in.read(b)) > 0) {
      baos.write(b, 0, len);
    }
    String bodyText = new String(baos.toByteArray(), NoticeConstant.CHARSET_UTF8);
    return bodyText;
  }
}
